package com.zyy.seckill.config;

import com.zyy.seckill.entity.User;
import com.zyy.seckill.service.IUserService;
import com.zyy.seckill.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *      自定义用户数据 接口处理器
 *
 * @Author: zyy
 * @DateTime: 2021/10/3 23:26
 */
@Component
public class UserArgumentResolve implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    /**
     *      条件判断  -->如果符合它的条件才能执行下面的 resolveArgument方法
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {

        Class<?> type = parameter.getParameterType(); //获取参数的类型
        return type == User.class; // 如果是的话就放行
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request =
                webRequest.getNativeRequest(HttpServletRequest.class);// 获取request
        HttpServletResponse response =
                webRequest.getNativeResponse(HttpServletResponse.class);//获取response

        return UserContext.getUser(); // 优化 使用 userContext 获取user用户

//        String ticket = CookieUtil.getCookieValue(request, "userTicket");
//
//        if (!StringUtils.hasLength(ticket)){
//            return null;
//        }
//        // 返回结果集
//        return userService.getUserByCookie(ticket,request,response);
    }
}
